<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <!-- <DeptTree class="w-1/4 xl:w-1/5" @select="handleSelect" /> -->
    <BasicTable @register="registerTable" :searchInfo="searchInfo">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate">{{ t('sys.account.addAccount') }}</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: t('sys.configuration.edit'),
                tooltip: t('sys.account.editAccountDetails'),
                onClick: handleEdit.bind(null, record),
              },
              {
                label: record.status
                  ? t('sys.configuration.forbidden')
                  : t('sys.configuration.startUsing'),
                color: record.status ? 'error' : 'success',
                tooltip: record.status
                  ? t('sys.account.forbiddenAccout')
                  : t('sys.account.startUsingAccout'),
                popConfirm: {
                  title: record.status ? t('sys.account.isDisabled') : t('sys.account.isStart'),
                  placement: 'left',
                  confirm: handleToggleStatus.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <AccountModal @register="registerModal" @success="handleSuccess" />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';

  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import {
    getAccountList,
    unableAPI,
    enableAPI,
    setaccountbind,
    getfacebooklist,
    getgetUserById,
  } from '@/api/demo/system';
  import { PageWrapper } from '@/components/Page';
  import DeptTree from './DeptTree.vue';

  import { useModal } from '@/components/Modal';
  import AccountModal from './AccountModal.vue';

  import { columns, searchFormSchema } from './account.data';
  import { useGo } from '@/hooks/web/usePage';
  import { useI18n } from '@/hooks/web/useI18n';
  import { template } from 'xe-utils';
  import { message } from 'ant-design-vue';

  defineOptions({ name: 'AccountManagement' });
  const friendsselectedRowKeyss = ref([]);
  const friendsonSelectChange = (selectedRowKeys: Key[]) => {
    friendsselectedRowKeyss.value = selectedRowKeys;
  };
  const handleTableChange = (pag: { pageSize: number; current: number }) => {
    console.log('====================================');
    console.log(pag);
    friendspagination.value = pag;
    console.log('====================================');
  };
  const friendsdataSource = ref([]);
  const friendscolumns = ref([
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: '账号',
      dataIndex: 'account',
    },
  ]);
  const friendspagination = ref({
    total: 0,
    current: 1,
    showSizeChanger: true,
    pageSize: 10,
  });
  const userId = ref('');
  const handleOk = () => {
    setaccountbind({ uid: userId.value, accountIds: friendsselectedRowKeyss.value }).then((res) => {
      console.log(res);
      if (res.code == 200) {
        AssignaccountsShow.value = false;
        friendsselectedRowKeyss.value = [];
        message.success(t('sys.api.operationSuccess'));
        reload();
      }
    });
  };
  const handleAssignAccounts = (record: Recordable) => {
    AssignaccountsShow.value = true;
    console.log(record);

    userId.value = record.userId;
    getfacebooklist().then((res) => {
      friendsdataSource.value = res.data;
    });
  };
  const AssignaccountsShow = ref(false);
  const go = useGo();
  const [registerModal, { openModal }] = useModal();
  const searchInfo = reactive<Recordable>({});
  const { t } = useI18n();
  const [registerTable, { reload, updateTableDataRecord, getSearchInfo }] = useTable({
    title: t('sys.account.accountList'),
    api: getAccountList,
    rowKey: 'userId',
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    handleSearchInfoFn(info) {
      return info;
    },
    actionColumn: {
      width: 120,
      title: t('sys.configuration.action'),
      dataIndex: 'action',
      // slots: { customRender: 'action' },
    },
    // 修复展开行问题：确保每一行都有唯一标识，并且根据需要设置手风琴模式
    accordion: true, // 启用手风琴模式，一次只展开一行
  });

  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    getgetUserById(record.userId).then((res) => {
      openModal(true, {
        record: res.data,
        isUpdate: true,
      });
    });
  }

  async function handleToggleStatus(record: Recordable) {
    let Data;
    if (record.status) {
      Data = await unableAPI(record.userId);
    } else {
      Data = await enableAPI(record.userId);
    }
    // 刷新表格数据
    reload();
  }

  function handleExport() {}

  function handleSuccess({ isUpdate, values }) {
    if (isUpdate) {
      // 演示不刷新表格直接更新内部数据。
      // 注意：updateTableDataRecord要求表格的rowKey属性为string并且存在于每一行的record的keys中
      const result = updateTableDataRecord(values.id, values);
    } else {
      reload();
    }
  }

  function handleSelect(deptId = '') {
    searchInfo.deptId = deptId;
    reload();
  }

  function handleView(record: Recordable) {
    go('/system/account_detail/' + record.id);
  }
</script>
